<?php


namespace app\controllers;

use app\forms\DemoForm;
use Yii;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\Response;

class FormController extends Controller
{
    /**
     *
     */
    public function actionIndex()
    {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $model = new DemoForm();
        $request = Yii::$app->getRequest();
        $cgi = array_merge($request->get(),$request->post());
        if (!$model->load($cgi, '')) {
            return ['赋值数据错误', 'cgi' => $cgi,'form' => $model->formName()];
        }
        if (!$model->validate()) {   // 数据验证错误
            return ['errors' => $model->getErrors(), 'firstErrors' => $model->getFirstErrors()];
        }
        // 数据验证通过
        return ['data' => $model->toArray()];
    }

    public function actionValidate()
    {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->getRequest();
        $cgi = array_merge($request->get(),$request->post());
        // 参数校验
        $form = new DemoForm();
        $form->load($cgi, '');
        if (!$form->validate()) {
            $errors = $form->getFirstErrors();
            //$errorMsg = reset($errors);
            //$errorMsg = current($errors);
            //$errorMsg = array_shift($form->firstErrors);
            $errorMsg = implode('', $form->firstErrors);
            return ['msg' => $errorMsg, 'errors' => $errors];
        }

        // 数据验证通过
        return [$form->toArray()];
    }

    public function actionValidate2()
    {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->getRequest();
        $cgi = array_merge($request->get(),$request->post());
        // 参数校验
        $form = new DemoForm();
        $from = $this->VdForm($form, null);

        // 数据验证通过
        return [$form->toArray()];
    }

    public function VdForm($form, $scenarios = null, $format = 'json')
    {

        if ($scenarios) {
            $form->setScenario($scenarios);
        }

        $request = \Yii::$app->request;
        $cgi = array_merge($request->get(),$request->post());
        $form->load($cgi, '');
        if (!$form->validate()) {
            $errors = $form->getErrors();
            if (empty($errors)) {
                return $form;
            }

            $msg = '';
            $labels = $form->attributeLabels();
            foreach ($errors as $key => $value) {
                if (isset($labels[$key])) {
                    foreach ($value as $k => $v) {
                        $value[$k] = str_replace($key, $labels[$key], $v);
                    }
                }
                $msg .= implode(',', $value) . ';';
            }
            $msg = trim($msg, ';');
            if ($format == 'string') {
                return $msg;
            }
            throw new \yii\web\HttpException(400, $msg);
        }

        return $form;
    }
}